import { createRouter, createWebHashHistory} from "vue-router";
import { constantRoutes } from "./routes";
import { useUserStore } from '@/store/modules/user';
import pinia from "@/store";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'
const router = createRouter({
    history: createWebHashHistory(),
    routes: constantRoutes
})
const userStore = useUserStore(pinia);
NProgress.configure({ showSpinner: false });
router.beforeEach(async (to, _from) => {
    NProgress.start();
    let token = userStore.userInfo.token;
    if (token) {
        if (to.path == '/login') {
            console.log('e');
            return '/home';
        }
        else {
            if (userStore.userInfo.username) {
                console.log('a');
                return true;
            }
            else {
                try {
                    await userStore.getUserInfo();
                    console.log('b');
                    return { ...to, replace: true };
                } catch (error) {
                    await userStore.logout();
                    console.log('c');
                    return '/login';
                }
            }
        }
    } else {
       if(to.path !== '/login'){
        return '/login';
       }
    }
    return true;
})
router.afterEach((_to, _from) => {
    NProgress.done();
})
export default router;
